package soar.test.xml.jdom;

import java.io.File;
import java.util.List;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

public class App
{
    public static void main(String[] args)
    {
        if (args.length < 1)
        {
            System.out.println(String.format("argument error"));
            return;
        }
        System.exit(new App().run(args[0]));
    }

    private int run(String xmldir)
    {
        try
        {
            jdom(xmldir);
        }
        catch (Exception e)
        {
            System.err.println(String.format("jdom fail: %s", e));
            return 1;
        }

        if (Conf.init(xmldir + "/conf.xml") == false)
        {
            System.err.println(String.format("conf init fail"));
            return 1;
        }

        return 0;
    }

    private void jdom(String xmldir) throws Exception
    {
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(new File(xmldir + "/data.xml"));

        Element root = doc.getRootElement();

        List<Element> persons = root.getChildren("person");
        for (Element person : persons)
        {
            int id = Integer.parseInt(person.getAttributeValue("id"));
            System.out.println("id: " + id);
            String username = person.getChildTextTrim("username");
            System.out.println("username:" + username);
            String password = person.getChildTextTrim("password");
            System.out.println("password: " + password);
        }
        System.out.println();

        List<Element> computers = root.getChildren("computer");
        for (Element computer : computers)
        {
            String type = computer.getChildTextTrim("type");
            System.out.println("type: " + type);
            if (type.equalsIgnoreCase("pc"))
            {
                String user = computer.getChildTextTrim("user");
                System.out.println("user: " + user);
            }
            else if (type.equalsIgnoreCase("server"))
            {
                Element user = computer.getChild("user");
                System.out.print("user:");
                List<Element> accounts = user.getChildren("account");
                for (Element account : accounts)
                {
                    String s = account.getTextTrim();
                    System.out.print(" " + s);
                }
                System.out.println();
            }
        }
        System.out.println();
    }
}
